package net.redxyz.repost.resource.action;

import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.core.Action;
import org.zhiqim.kernel.util.Urls;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.ZTable;
import org.zhiqim.orm.dbo.Selector;

import net.redxyz.repost.resource.SessionUser;
import net.redxyz.top.dbo.sys.SysApp;

/**
 * 商家客户端接入登录失败
 * 
 * @version v7.0.1 @author lgz 2021-10-20 新建与整理
 */
public class OpenAppLoginSuccAction implements Action {
    @Override
    public void execute(HttpRequest request) throws Exception {
        
        SessionUser sessionUser = request.getSessionUser(SessionUser.class);
        if (sessionUser == null || !sessionUser.isLoginOpenApp()) {
            request.setRedirect("/web.htm");
            return;
        }
        
        SysApp app = ORM.get(ZTable.class).item(SysApp.class, new Selector("appKey", sessionUser.getOpenAppKey()));
        if (app == null || app.getAppStatus() == 1) {
            request.setRedirect("/open-app-login-err.htm?id=" + sessionUser.getOpenAppKey());
            return;
        }
        
        if (Validates.isUrl(app.getRedirectUrl())) {
            String sub_state = request.getParameterNoFilter("sub_state", "");
            String url = app.getRedirectUrl();
            url = Urls.add(url, "userNick", sessionUser.getNick());
            url = Urls.add(url, "state", sub_state);
            request.setRedirect(url);// 设置重定向
            // 注意这里不return 因为需要做第一次登录回调信息
        }
    }
}
